#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>

#include "../include/server.h"
#include "../include/serial.h"
#include "../include/json_par.h"
#include "../include/logger.h"
#include "../include/shared_data.h"

#define PORT 8080
#define BUFFER_SIZE 1024

// 在这里定义和初始化共享的数据包和互斥锁
struct DataPacket shared_packet;
pthread_mutex_t packet_mutex = PTHREAD_MUTEX_INITIALIZER;


void *handle_client(void *arg) {
    int client_socket = *((int *)arg);
    char buffer[BUFFER_SIZE];
    int bytes_received;
    JsonData json_struct;
    
    while (1) {
        int uart_fd;
        
        memset(buffer, 0, sizeof(buffer));
        bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
        if (bytes_received == -1) {
            //perror("接收数据失败");
            writeLog(ERROR,__FILE__,__func__,"接收数据失败\n");
            break;
        }
        if (bytes_received == 0) {
            //printf("客户端断开连接\n");
            writeLog(INFO,__FILE__,__func__,"客户端断开连接\n");
            break;
        }
        if(json_struct.destination == 0){
            uart_fd = serial_fd[0];
            //writeLog(INFO,__FILE__,__func__,"uart_fd = %d\n",uart_fd);
        }
        else if(json_struct.destination == 1){
            uart_fd = serial_fd[1];
            //writeLog(INFO,__FILE__,__func__,"uart_fd = %d\n",uart_fd);
        }
        else{

        }
        
        // 处理客户端发送的数据
        // 使用解析模块解析JSON数据
        memset(&json_struct,0,sizeof(JsonData));
        if (parse_json(buffer,&json_struct) == 0) {           
            // JSON解析成功，继续处理数据
            // 使用互斥锁保护共享数据
            pthread_mutex_lock(&packet_mutex);
            shared_packet.client_socket = client_socket;
            shared_packet.source = json_struct.source;
            shared_packet.destination = json_struct.destination;
            shared_packet.type = json_struct.type;
            pthread_mutex_unlock(&packet_mutex);

            send_serial_data(uart_fd,json_struct.cmd,json_struct.cmd_len); 
            
        } else {
            // JSON解析失败，处理错误
            //printf("json error\n");
            writeLog(ERROR,__FILE__,__func__,"json error\n");
        }

    }
    // 关闭客户端套接字
    close(client_socket);
    writeLog(INFO,__FILE__,__func__,"Client disconnected\n");
    //printf("Client disconnected\n");

    return NULL;
}

void start_server() {
    int server_socket, client_socket;
    struct sockaddr_in server_address, client_address;
    socklen_t client_address_len = sizeof(client_address);

    // 创建套接字
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        //perror("Socket creation failed");
        writeLog(ERROR,__FILE__,__func__,"Socket creation failed\n");
        exit(EXIT_FAILURE);
    }

    // 端口复用
    int opt = 1;
    setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt));

    // 设置服务器地址结构
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(PORT);
    server_address.sin_addr.s_addr = INADDR_ANY;

    // 绑定套接字到IP地址和端口
    if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) == -1) {
        //perror("Binding failed");
        writeLog(ERROR,__FILE__,__func__,"Binding failed\n");
        exit(EXIT_FAILURE);
    }

    // 开始监听连接请求
    if (listen(server_socket, 5) == -1) {
        //perror("Listening failed");
        writeLog(ERROR,__FILE__,__func__,"Listening failed\n");
        exit(EXIT_FAILURE);
    }
    writeLog(INFO,__FILE__,__func__,"Server listening on port %d...\n",PORT);   
    //printf("Server listening on port %d...\n", PORT);


    while(1) {
        // 接受客户端连接
        client_socket = accept(server_socket, (struct sockaddr *)&client_address, &client_address_len);
        if (client_socket == -1) {
            //perror("Accepting connection failed");
            writeLog(ERROR,__FILE__,__func__,"Accepting connection failed\n");
            exit(EXIT_FAILURE);
        }
        //printf("接受来自 %s:%d 的连接\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
        writeLog(INFO,__FILE__,__func__,"接受来自 %s:%d 的连接\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); 


        
        // 创建线程来处理客户端连接
        pthread_t client_thread;
        if (pthread_create(&client_thread, NULL, handle_client, (void *)&client_socket) != 0) {
            //perror("无法创建线程");
            writeLog(ERROR,__FILE__,__func__,"无法创建线程\n");
            continue;
        }
        
        // 分离线程，使其在结束时自动释放资源
        pthread_detach(client_thread);

    }
     // 关闭服务器套接字
    close(server_socket);

}

